/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#ifndef SHARED_BASE_MUTEX_WIN32_H_
#define SHARED_BASE_MUTEX_WIN32_H_

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>


class MutexImpl
{
protected:
	MutexImpl(void);
	~MutexImpl(void);

	bool lockImpl(void);
	bool tryLockImpl(void);
	bool tryLockImpl(long milliseconds);
	void unlockImpl(void);

	bool isLockedImpl(void) const;

private:
	CRITICAL_SECTION _cs;
	volatile bool _locked;
};


typedef MutexImpl FastMutexImpl;


inline bool MutexImpl::lockImpl(void)
{
	EnterCriticalSection(&_cs);
	_locked = true;
	return true;
}

inline bool MutexImpl::tryLockImpl(void)
{
	if (TryEnterCriticalSection(&_cs) != FALSE) {
		_locked = true;
		return true;
	}
	return false;
}

inline void MutexImpl::unlockImpl(void)
{
	_locked = false;
	LeaveCriticalSection(&_cs);
}

inline bool MutexImpl::isLockedImpl(void) const
{
	return _locked;
}

#endif /* SHARED_BASE_MUTEX_WIN32_H_ */
